package com.swordget.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.swordget.dao.DataHandlerDao;
import com.swordget.entity.ColumnDesign;
import com.swordget.entity.TableDesign;
import com.swordget.entity.bo.ImportResolveBo;
import com.swordget.entity.bo.ModifyBo;
import com.swordget.entity.po.CheckLogPo;
import com.swordget.entity.po.DataQueryPo;
import com.swordget.entity.vo.InputStructVo;
import com.swordget.entity.vo.SimplePageRequestVo;
import com.swordget.exception.VerifyFailException;
import com.swordget.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.swordget.commons.ColumnType.NUMBER;
import static com.swordget.commons.PatternUtil.NUMBER_CHECK;
import static com.swordget.commons.SimpleFinalUtil.*;


/**
 * @Author: David
 * @Date: Created in 10:54 2020/4/8
 * @Description: 数据查询服务实现
 * @Modified By:
 * @Version: 0.0.1
 */
@Service
public class DataHandlerServiceImp implements DataHandlerService {

    private TableDefinitionService tableDefinitionService;

    private DataHandlerDao dataQueryDao;

    private DataVerifyService dataVerifyService;

    private LogService logService;

    private TableManagerService tableManagerService;

    @Autowired
    public DataHandlerServiceImp(TableDefinitionService tableDefinitionService, DataHandlerDao dataQueryDao,
                                 DataVerifyService dataVerifyService, LogService logService,
                                 TableManagerService tableManagerService) {
        this.tableDefinitionService = tableDefinitionService;
        this.dataQueryDao = dataQueryDao;
        this.dataVerifyService = dataVerifyService;
        this.logService = logService;
        this.tableManagerService = tableManagerService;
    }


    @Override
    public DataQueryPo dataQuery(final SimplePageRequestVo pageVo) {
        final String loginId = pageVo.getLoginId();
        final String tableId = pageVo.getTableId();
        final Integer rows = pageVo.getRows();
        final Integer page = pageVo.getPage();
        final String dataStatus = pageVo.getDataStatus();
        JSONArray params = pageVo.getQueryParams();
        //检查前台传入的参数是否符合要求
        String tableName = this.checkParams(rows, page, loginId, tableId);
        //调用表结构服务获取表列结构
        List<String> columns = tableDefinitionService.getColumns(tableId, true, true);
        this.checkQueryParams(params, columns);
        //判断数据状态以显示不通的数据
        params = addDataStatus(params, dataStatus);
        List<String> types = tableDefinitionService.getColumnTypes(tableId, true, true);

        List<ColumnDesign> columnDesigns = tableDefinitionService.getColumnDesigns(tableId, true, true);


        String dataSourceId = "";
        TableDesign tableDesign = tableManagerService.flinOne(tableId);
        if (Objects.nonNull(tableDesign)) {
            dataSourceId = tableDesign.getDataSourceId();
        }
        //执行查询
        DataQueryPo dataQueryPo = dataQueryDao.query(rows, page, params, tableName, columns, types, columnDesigns, dataSourceId);
        return dataQueryPo;
    }


    @Override
    public JSONArray addDataStatus(JSONArray params, String dataStatus) {
        params = null == params ? new JSONArray() : params;
        JSONObject jsonObject = new JSONObject();
        if (SUBMIT.equals(dataStatus)) {
            //待提交
            jsonObject.put("name", "status");
            jsonObject.put("value", "['0', '-1', '-2']");
        } else if (CHECK.equals(dataStatus)) {
            //待审核
            jsonObject.put("name", "status");
            jsonObject.put("value", "[1,2]");
        } else if (PASS.equals(dataStatus)) {
            //审核通过
            jsonObject.put("name", "status");
            jsonObject.put("value", "[2]");
        }
        params.add(jsonObject);
        return params;
    }

    @Override
    public boolean dataSubmit(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //只能提交待提交的数据
       /* JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "0");
        searchParams.add(status);*/
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        //如果有搜索条件就是按搜索条件提交不需要进行额外处理
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());

        //添加日志记录
        //logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行提交操作", "提交", "");
        return dataQueryDao.dataModify(tableName, searchParams, handleDate, handleTime, loginId, "", "2");
    }

    @Override
    public Integer notPass(TableDesign tableDesign, JSONArray searchParams, List<String> list, String dataStatus, String loginId, String notPassMark) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);

        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        //校验是否包含有操作名的数据
        Integer result = dataQueryDao.checkNullOrNotContainsHanleName(tableName, searchParams);
        if (result < 2) {
            return result;
        }

        ////只能审核不通过提交的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "2");
        searchParams.add(status);

        //如果有搜索条件就是按搜索条件提交不需要进行额外处理
        String handleName = loginId;
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        //添加日志记录
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行审核不通过操作", "审核不通过", "");
        return dataQueryDao.dataModify(tableName, searchParams, handleDate, handleTime, loginId, "审核不通过", notPassMark, "-2") == true ? 3 : 2;

    }

    /*@Override
    public boolean notPass(TableDesign tableDesign, JSONArray searchParams, List<String> list, String dataStatus, String loginId, String notPassMark) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //只能审核不通过提交的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "2");
        searchParams.add(status);
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId()) + TMP_SUFFIX;
        //如果有搜索条件就是按搜索条件提交不需要进行额外处理
        String handleName = loginId;
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        //添加日志记录
        //logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行审核不通过操作", "审核不通过", "");
        return dataQueryDao.dataModify(tableName, searchParams, handleDate, handleTime, loginId, "审核不通过", notPassMark, "-2");
    }*/

    /**
     * 同意申请
     * 同意申请就是直接删除
     *
     * @param tableDesign  表结构
     * @param searchParams 搜索数据
     * @param list         集合
     * @param loginId      数据状态
     * @param dataStatus   数据状态
     * @param orgId
     * @return
     */
    @Override
    public boolean agreeApply(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus, String orgId) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //只能删除申请删除的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "1");
        searchParams.add(status);
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
      /*  int result = dataQueryDao.checkNullOrContainsHanleName(tableName, searchParams);
        System.out.println("result=="+result);
        if(result < 2){
            return false;
        }*/

        //处理申请删除的数据
        JSONObject removeJsonObject = new JSONObject();
        removeJsonObject.put("name", "HANDLENAME");
        removeJsonObject.put("value", "申请删除");
        searchParams.add(removeJsonObject);
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行同意申请删除操作", "同意申请", "");
        dataQueryDao.remove(tableName, searchParams, "");

        //处理申请修改的数据
        searchParams.remove(removeJsonObject);
        JSONObject updateJsonObject = new JSONObject();
        updateJsonObject.put("name", "HANDLENAME");
        updateJsonObject.put("value", "申请修改");
        searchParams.add(updateJsonObject);
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行同意申请修改操作", "同意申请", "");
        return dataQueryDao.agreeDataModify(tableName, searchParams, handleDate, handleTime, loginId, "", "0", "0");
    }

    @Override
    public boolean rejectApply(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //只能拒绝申请要删除的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "1");
        searchParams.add(status);
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行拒绝申请操作", "拒绝申请", "");
        return dataQueryDao.dataModify(tableName, searchParams, handleDate, handleTime, loginId, "", "0");
    }

   /* @Override
    public boolean pass(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus, String orgId) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //只能审核待审核的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "2");
        searchParams.add(status);
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        long total = dataQueryDao.getTotal(tableName + TMP_SUFFIX, searchParams);
        boolean isPass = dataQueryDao.pass(tableName, searchParams, handleDate, handleTime, loginId);
        //记录日志
        if (isPass) {
            if (list.size() == 1) {
                logService.addLog(loginId, "审核表：" + tableName + "数据id：" + list.get(0), "逐条审核", orgId);
            } else {
                logService.addLog(loginId, "审核表：" + tableName + "审核时间："
                        + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "审核数量:" + total, "批量审核", orgId);
            }
        }
        return isPass;
    }*/

    @Override
    public Integer pass(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);

        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }


        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());

        String tableNameSuf = tableName;

        //校验是否包含有操作名的数据
        Integer result = dataQueryDao.checkNullOrNotContainsHanleName(tableNameSuf, searchParams);
        if (result < 2) {
            return result;
        }

        //只能审核通过提交的数据
        JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "2");
        searchParams.add(status);

        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        //添加日志记录
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行审核通过操作", "审核通过", "");

        return dataQueryDao.pass(tableName, searchParams, handleDate, handleTime, loginId, "2", "9", "") == true ? 3 : 2;

    }

    @Override
    public boolean applyRemove(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);

        String dataSourceId = "";
        TableDesign design = tableManagerService.flinOne(tableDesign.getTableId());
        if (Objects.nonNull(tableDesign)) {
            dataSourceId = design.getDataSourceId();
        }

        //只能审核待审核的数据
       /* JSONObject status = new JSONObject();
        status.put("name", "STATUS");
        status.put("value", "0");
        searchParams.add(status);*/
        //如果id集合不为空则是按 id
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        String tableNameSuf = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        //添加日志记录
        //logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行申请删除操作", "申请删除", "");
        boolean flag = false;
        if (SUBMIT.equals(dataStatus)) {
            //待审核
            // flag = dataQueryDao.applyDataModify(tableNameSuf, searchParams, handleDate, handleTime, loginId, "申请删除", "1");
            flag = dataQueryDao.remove(tableName, searchParams, dataSourceId);
        } else if (CHECK.equals(dataStatus)) {
            //待审核
            flag = dataQueryDao.applyDataModify(tableNameSuf, searchParams, handleDate, handleTime, loginId, "申请删除", "1");
        } else if (PASS.equals(dataStatus)) {
            //审核通过
            flag = dataQueryDao.passDataModify(tableName, searchParams, handleDate, handleTime, loginId, "申请删除", "1");
        }

        return flag;
    }

    @Override
    //申请修改
    public boolean applyModify(TableDesign tableDesign, JSONArray searchParams, List<String> list, String loginId, String dataStatus) {
        //添加数据状态
        searchParams = addDataStatus(searchParams, dataStatus);
        //如果id集合不为空则是按 idagreeApply
        if (null != list && list.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "SERIALNO");
            jsonObject.put("value", "[" + String.join(",", list) + "]");
            searchParams.add(jsonObject);
        }
        String handleDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String handleTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
        String tableNameSuf = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        //添加日志记录
        logService.addLog(loginId, "对" + tableDesign.getTableCN() + "表进行申请修改操作", "申请修改", "");
        boolean flag = false;
        if (CHECK.equals(dataStatus)) {
            //待审核
            flag = dataQueryDao.applyDataModify(tableNameSuf, searchParams, handleDate, handleTime, loginId, "申请修改", "1");
        } else if (PASS.equals(dataStatus)) {
            //审核通过
            flag = dataQueryDao.passDataModify(tableName, searchParams, handleDate, handleTime, loginId, "申请修改", "1");
        }
        return flag;
    }

    @Override
    public List<List<String>> queryDataByStatus(int rows, int page, String tableName, JSONArray queryParam,
                                                List<String> columns, List<String> types, List<ColumnDesign> columnDesigns,
                                                String[] serials, String dataSourceId) {
        return dataQueryDao.queryByListByStatus(rows, page, queryParam, tableName, columns, types, columnDesigns, serials, dataSourceId);
    }


    @Override
    public List<List<String>> queryData(int rows, int page, String tableName, JSONArray queryParam,
                                        List<String> columns, List<String> types) {
        return dataQueryDao.queryByList(rows, page, queryParam, tableName, columns, types);
    }

    @Override
    public int dataAdd(File loadData, String tableName, List<String> columns) throws Exception {
        return dataQueryDao.insert(loadData, tableName, columns);
    }

    @Override
    public boolean dataAdd(String tableName, String tableNameTmp, String tableId, String importId) {
        List<String> columns = tableDefinitionService.getColumns(tableId, true, false);
        return dataQueryDao.copyData(tableName, tableNameTmp, columns, importId);
    }

    @Override
    public boolean removeByImportId(String tableNameTmp, String importId) {
        return dataQueryDao.removeByImportId(tableNameTmp, importId);
    }

    @Override
    public boolean addCheckLog(ImportResolveBo testBo) {
        //查询下表中文名
        String comment = tableDefinitionService.getTableComment(testBo.getLoginId(), testBo.getTableId());
        CheckLogPo checkLogPo = CheckLogPo.builder()
                .serialNo(testBo.getImportId())
                .tableId(testBo.getTableId())
                .tableComment(comment)
                .createUser(testBo.getLoginId())
                .createDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                .createTime(new SimpleDateFormat("HH:mm:dd").format(new Date()))
                .makeStatus("0")
                .build();

        return dataQueryDao.addCheckLog(checkLogPo);
    }

    @Override
    public boolean dataAdd(TableDesign tableDesign, List inputStructVos, String loginId, String orgId) {
        final String tableId = tableDesign.getTableId();

        String dataSourceId = "";
        TableDesign design = tableManagerService.flinOne(tableId);
        if (Objects.nonNull(design)) {
            dataSourceId = design.getDataSourceId();
        }

        //检查前台传入的参数是否符合要求
        ModifyBo modifyBo = dataHandlerAndVerify(tableDesign, inputStructVos, loginId, "INSERT");
        //添加主键等隐藏参数
        this.addParams(modifyBo, loginId);
        this.handlerMap(modifyBo);
        //处理map得到 names 集合和 values 集合
        List<String> names = modifyBo.getNames();
        List<String> values = modifyBo.getValues();
        String keyValue = modifyBo.getKeyValue();
        //生成插入格式
        String columns = String.join(",", names);
        String columnValues = String.join(",", values);
        //插入到临时表中
        String tableName = modifyBo.getTableName();
        //调用校验服务进行数据库校验,如果失败会抛出异常
        dataVerifyService.verify(tableId, tableName, columns, columnValues, keyValue);
        //插入数据
        boolean isInsert = dataQueryDao.insert(tableName, columns, columnValues, dataSourceId);
        if (isInsert) {
            //添加日志记录
            logService.addLog(loginId, "插入表：" + tableName + "数据id：" + keyValue, "插入数据", orgId);
        }
        return isInsert;
    }

    @Override
    public boolean dataAdd(String tableName, List<String> columns, String[][] datas, String loginId) {
        //校验
        System.out.println("线程：-" + Thread.currentThread().getName() + "调用");
        return dataQueryDao.insert(tableName, columns, datas);
    }

    @Override
    public boolean dataRemove(TableDesign tableDesign, List<String> list, String loginId) {
        //校验
        String tableName = tableDefinitionService.getTableName(loginId, tableDesign.getTableId());
        List<String> params = new ArrayList<>(list.size());
        //处理集合
        for (String value : list) {
            value = "'" + value + "'";
            params.add(value);
        }
        //调用删除
        return dataQueryDao.remove(tableName, params);
    }


    @Override
    public boolean dataModify(TableDesign tableDesign, List inputStructVos, String loginId, String orgId) {
        ModifyBo modifyBo = dataHandlerAndVerify(tableDesign, inputStructVos, loginId, "UPDATE");

        String dataSourceId = "";
        TableDesign design = tableManagerService.flinOne(tableDesign.getTableId());
        if (Objects.nonNull(design)) {
            dataSourceId = design.getDataSourceId();
        }

        //处理主键等参数
        //this.modifyParams(modifyBo, loginId);
        Map<String, String> valueMap = modifyBo.getValueMap();
        String keyValue = valueMap.get("SERIALNO");
        if (StringUtils.isBlank(keyValue)) {
            throw new VerifyFailException("请检查您的请求参数!");
        }
        //valueMap.put("CREATEUSER", loginId);
        modifyBo.setKeyValue(keyValue);
        //添加操作时间等参数
        valueMap.put("HANDLEDATE", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        valueMap.put("HANDLETIME", new SimpleDateFormat("HH:mm:ss").format(new Date()));
        valueMap.put("HANDLEUSER", loginId);
        valueMap.put("STATUS", "0");
        //处理map
        this.handlerMap(modifyBo);
        List<String> names = modifyBo.getNames();
        List<String> values = modifyBo.getValues();
        //处理的是临时表
        final String tableName = modifyBo.getTableName();
        final String tableId = tableDesign.getTableId();
        //final String keyValue = modifyBo.getKeyValue();
        ////调用校验服务进行数据库校验,如果失败会抛出异常
        dataVerifyService.verify(tableId, tableName, String.join(",", names),
                String.join(",", values), keyValue);
        boolean f = dataQueryDao.modify(tableName, names, values, keyValue, dataSourceId);
        if (f) {
            //添加日志记录
            logService.addLog(loginId, "修改表：" + tableName + "数据id：" + keyValue, "修改数据", orgId);
        }
        return f;
    }


    /**
     * 校验查询参数
     *
     * @param queryParams
     * @param columns
     */
    @Override
    public void checkQueryParams(JSONArray queryParams, List<String> columns) {
        //校验下查询参数
        if (queryParams != null) {
            for (int i = 0; i < queryParams.size(); i++) {
                JSONObject jsonObject = queryParams.getJSONObject(i);
                String name = jsonObject.getString("name");
                if (!columns.contains(name)) {
                    throw new VerifyFailException("您输入的查询参数不正确!");
                }
            }
        }
    }

    @Override
    public int getTotal(String tableName, JSONArray queryParams, String[] serials, String dataSourceId) {
        return dataQueryDao.getTotal(tableName, queryParams, serials, dataSourceId);
    }


    private ModifyBo dataHandlerAndVerify(TableDesign tableDesign, List inputStructVos, String loginId, String state) {
        final String tableId = tableDesign.getTableId();
        //检查前台传入的参数是否符合要求
        String tableName = tableDefinitionService.getTableName(loginId, tableId);
        //调用表结构服务获取表列结构
        List<ColumnDesign> designs = tableDefinitionService.getColumnDesigns(tableId, true, false);
        //对传入的字段进行简单的检查
        Map<String, String> valueMap = this.checkStruct(inputStructVos, designs, tableName, state);
        ModifyBo modifyBo = new ModifyBo();
        modifyBo.setTableName(tableName);
        modifyBo.setValueMap(valueMap);
        return modifyBo;
    }

    private void handlerMap(ModifyBo modifyBo) {
        Map<String, String> map = modifyBo.getValueMap();
        List<String> names = new ArrayList<>(map.size());
        List<String> values = new ArrayList<>(map.size());
        for (String key : map.keySet()) {
            String value = map.get(key);
            names.add(key);
            /*if (value == null) {value = "";}
            values.add("'" + value + "'");*/
            if (StringUtils.isBlank(value)) {
                values.add(null);
            } else {
                String newValue = value;
                if (value.indexOf("'") != -1) {
                    newValue = value.replaceAll("'", "''");

                }
                values.add("'" + newValue + "'");
            }
        }
        modifyBo.setNames(names);
        modifyBo.setValues(values);
    }


    private void modifyParams(ModifyBo modifyBo, String loginId) {
        Map<String, String> valueMap = modifyBo.getValueMap();
        String keyValue = valueMap.remove("SERIALNO");
        if (StringUtils.isBlank(keyValue)) {
            throw new VerifyFailException("请检查您的请求参数!");
        }
        valueMap.put("CREATEUSER", loginId);
        modifyBo.setKeyValue(keyValue);
        //修改时间待定
    }

    private void addParams(ModifyBo modifyBo, String loginId) {
        //添加业务字段
        //TODO: 随机生成的唯一值，可能存在高并发条件下的重复，可以使用UUID替换或采用其他方式解决，
        //TODO: 由于业务很难产生高并发场景，这里使用性能稍微好点的随机数
        Map<String, String> map = modifyBo.getValueMap();
        String keyValue = System.currentTimeMillis() + Math.round(Math.random() * 100000) + "";
        modifyBo.setKeyValue(keyValue);
        map.put("SERIALNO", keyValue);
        map.put("CREATEDATE", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        map.put("CREATETIME", new SimpleDateFormat("HH:mm:ss").format(new Date()));
        map.put("CREATEUSER", loginId);
        map.put("HANDLEDATE", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        map.put("HANDLETIME", new SimpleDateFormat("HH:mm:ss").format(new Date()));
        /*   map.put("HANDLENAME", "");*/
        map.put("HANDLEUSER", loginId);
        map.put("STATUS", "0");
        map.put("DATASOURCE", "手工录入");
    }

    private String checkParams(Integer rows, Integer page, String loginId, String tableId) {
        //对rows的大小要限制，否则恶意调用会拖垮数据库
        if (rows <= 0 || page <= 0 || rows > 100) {
            throw new VerifyFailException("参数无效");
        }
        return tableDefinitionService.getTableName(loginId, tableId);
    }


    private Map<String, String> checkStruct(List<InputStructVo> inputStructVos, List<ColumnDesign> columns, String tableName, String state) {
        Map<String, String> tmpMap = new HashMap<>();
        //这里使用临时MAP 防止有些多余参数注入
        Map<String, String> map = new HashMap<>();
        String thatSerialno = "";
        for (InputStructVo structVo : inputStructVos) {
            // 获取序列编号
            if ("SERIALNO".equals(structVo.getName())) {
                thatSerialno = structVo.getValue();
            }
            tmpMap.put(structVo.getName(), structVo.getValue());
        }
        for (ColumnDesign column : columns) {
            String name = column.getName();
            String comment = column.getComment();
            String value = tmpMap.get(name);
            //参数不能为空校验,通过map校验即使前台不传这个值也能判断出来
            if (YES.equals(column.getNotNull()) && NO.equals(column.getIsHidden()) && StringUtils.isBlank(value)) {
                throw new VerifyFailException("请检查必输项是否填写完整!");
            }
            if (YES.equals(column.getNotRepeat())) {
                int n = dataQueryDao.getCount(tableName, name, value);
                // int n1=dataQueryDao.getCount(tableName, name, value);
                if ("INSERT".equals(state)) {
                    if (n > 0) {
                        throw new VerifyFailException(comment + "不可重复");
                    }
                } else {
                    if (n > 1) {
                        throw new VerifyFailException(comment + "不可重复");
                    }

                    String serialno = dataQueryDao.getSerialno(tableName, name, value);

                    // 如果修改的数据和数据库存在的不是同一条
                    if (StringUtils.isNotBlank(serialno) && !thatSerialno.equals(serialno)) {
                        throw new VerifyFailException(comment + "不可重复");
                    }
                }
            }

            if (StringUtils.isNotBlank(value) && NO.equals(column.getIsHidden())) {
                //字段长度校验
                try {
                    int width = column.getWidth();
                    String data = value;
                    if (NUMBER.equals(column.getType()) && column.getPoint() > 0) {
                        width = column.getWidth() - column.getPoint();
                        int index = value.indexOf(".");
                        if (index > -1) {
                            data = value.substring(0, index);
                        }
                    }
                    if (data.getBytes("UTF-8").length > width) {
                        throw new VerifyFailException(comment + "字段长度不正确!");
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new VerifyFailException(comment + "无法按字节解析数据");
                }

                //值类型校验如果是number不允许数字外的字符
                if (NUMBER.equals(column.getType())
                        && !NUMBER_CHECK.matcher(value).find()) {
                    throw new VerifyFailException(comment + "字段必须为数值型");
                }

                //number类型要校验小数位
               /* if (NUMBER.equals(column.getType())
                        && value.indexOf(".") > -1
                        && value.substring(value.indexOf(".")+1).length() > column.getPoint()) {
                    throw new VerifyFailException(comment + "字段数值长度不正确");
                }*/
                //日期格式校验
                if (DATE_BOX.equals(column.getContextType())) {
                    SimpleDateFormat sdf = new SimpleDateFormat(column.getDateFormat());
                    try {
                        sdf.parse(value);
                    } catch (ParseException e) {
                        throw new VerifyFailException(comment + "无法解析日期格式,请确认输入的日期格式正确\n");
                    }
                }
            }
            //有值的才修改
            map.put(name, value);
        }
        return map;
    }
}
